package zhuzx.solution.ir;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.zhuzx.util.FileOperationUtil;
import org.zhuzx.util.GeneralUtil;
import org.zhuzx.util.JdbcUtil;

import zhuzx.solution.ExportHelper;
import zhuzx.solution.ir.IrDataHelper.IrUser;

public class IrUserDeleter {
	
	public static void main(String[] args) {
		String org = "";
		String[] names = {"杨锦权"};//注意：有delete语句
		String msg = delete(org, names);
		IrDataHelper.showResult(msg);
	}

	static String delete(String org, String... names) {
		List<IrUser> list = findAll(org, names);
		if (list == null) {
			return null;
		}
		List<String> userIds = new ArrayList<>();
		List<String> userStr = new ArrayList<>();
		for (IrUser user : list) {
			userIds.add(user.id);
			userStr.add(user.name + "，" + user.fullOrgName + "。");
		}
		String idsStr = GeneralUtil.getCombinedString(userIds, "','");
		String sql = "select * from oa.ir_address_book where user_id in('"
				+ idsStr + "')";
		System.out.println("backup query sql :\n" + sql);
		List<Map<String,String>> userDataList = JdbcUtil.executeQuery(sql);
		StringBuilder backup = new StringBuilder();
		for (Map<String, String> map : userDataList) {
			String subBackup = JdbcUtil.createInsertSql("oa.ir_address_book", map);
			backup.append(subBackup).append(";\n");
		}
		backup.append("\n");
		String fileName = "C:\\Users\\zhuzexiang\\Desktop\\IR-exp\\BackupFiles"
				+ "\\ir_address_book删除备份";
		FileOperationUtil.writeToFile(backup.toString().getBytes(StandardCharsets.UTF_8),
				fileName + ".sql", false);
		String csv = ExportHelper.createCsvString(userDataList);
		FileOperationUtil.writeToFile(csv.getBytes(StandardCharsets.UTF_8),
				fileName + ".csv", false);
		
		String delSql = sql.replace("select *", "delete");
		int rows = IrDataHelper.update("delete user", delSql, Arrays.toString(names));
		String res = "已删除" + rows + "名员工：\n" + GeneralUtil.getCombinedString(userStr, "\n");
		return res;
	}
	
	private static List<IrUser> findAll(String org, String... names) {
		if (GeneralUtil.isEmpty(names)) {
			throw new IllegalArgumentException();
		}
		List<IrUser> list = new ArrayList<>();
		for (int i = 0; i < names.length; i++) {
			IrUser user = IrDataHelper.findUser(names[i], org);
			if (user == null) {
				return null;//需要人工介入
			} else {
				list.add(user);
			}
		}
		return list;
	}
	
}